package com.wh.pc;

import java.util.Enumeration;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * JUC下 Condition精准唤醒
 */
public class JUC_Condi_Sc {
    public static void main(String[] args) {
        Sc3 sc3 = new Sc3();
        new Thread(()->{
            for(int i=0;i<10;i++){
                sc3.printA();
            }
        },"A").start();
        new Thread(()->{
            for(int i=0;i<10;i++){
                sc3.printB();
            }
        },"B").start();
        new Thread(()->{
            for(int i=0;i<10;i++){
                sc3.printC();
            }
        },"C").start();
    }
}

class Sc3 {
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();//A
    private Condition condition2 = lock.newCondition();//B
    private Condition condition3 = lock.newCondition();//C
    private int number = 1; //1->A  2->B  3->C


    public void printA() {
        lock.lock();
        try {
            while (number != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "-->" + number);
            number++;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            while (number != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "-->" + number);
            number++;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (number != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "-->" + number);
            number = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}